package Gui.Dialogs;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

import Cards.DealCard;
import Main.Defines;

public class DealCardDialog extends JDialog
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5576051974883456418L;

	JLabel Title;
	JLabel Cost;
	JLabel Value;
	private void buildUI(final DealCard DrawnCard){
		//Draws the info for DrawnCard
		Title = new JLabel(DrawnCard.getName());
		Cost = new JLabel("It Costs: " + DrawnCard.getCost());
		Value = new JLabel("It's Worth: " + DrawnCard.getValue());
		JButton Buy = new JButton("Buy");
		JButton Cancel = new JButton("No Thanks");
		Buy.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				if (Defines.CP().getCash() >= DrawnCard.getCost())
				{
					Defines.CP().RemoveCash(DrawnCard.getCost());
					
				}
				else{
					// TODO OPEN NEW JDIALOG to check if this is correct
					// round his money down and automatically get money from bank
					
					int remainder = Defines.CP().getCash() % 1000; // MAGIC NUMBER 1000 should be LOAN_INC_AMOUNT, set in player class
					int moneyNeeded =  DrawnCard.getCost() - Defines.CP().getCash();
					int addToLoanAmount = moneyNeeded + (1000 - moneyNeeded % 1000); // MAGIC NUMBER

					AskForLoanDialog showDialog = new AskForLoanDialog(Defines.CP().getID(),  moneyNeeded, " for this deal card.", addToLoanAmount);
					
					if(showDialog.isClosed() && showDialog.isLoanOK()){
						Defines.CP().setLoan(Defines.CP().getLoan()+addToLoanAmount);
						Defines.CP().setCash(remainder);
						Defines.CP().addDealCard(DrawnCard);
					}
				}
				
				dispose();
			}
		});
		Cancel.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				dispose();
			}
		});

		add(Title);
		add(Cost);
		add(Value);
		add(Buy);
		add(Cancel);

	}
	public DealCardDialog(JFrame parent, final DealCard DrawnCard)
	{
		super(parent, "You Recieved A Deal Card", true);
		
		setLayout(new GridLayout(0, 1, 0, 10));
		setLocationRelativeTo(parent);
		buildUI(DrawnCard);
	
		pack();
		if(getTitle() != null){
			FontMetrics fm = getFontMetrics(getFont());
			int width = fm.stringWidth(getTitle()) + 75; // MAGIC NUMBER, 75 is size of a "typical" window icon
			width = (int) Math.max(width*1.2, getPreferredSize().getWidth());
			setSize(new Dimension(width, getHeight()));
		}
		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}
}
